<?php

namespace app\index\controller\tan;

use think\Controller;
use think\Request;
use think\Session;
use think\Db;
use app\index\model\tan\Store as S;
use app\index\controller\Sms\AliYunSms;
/**
 * 门店管理
 */
class Store extends Controller
{
    use UploadFileTrait;


    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(S $s)
    {
        ReturnData::ok($s->alias("s")->join("users u ","u.id=s.user_id")  ->where([
            's.business_id'=>Session::get("user.id"),
            "s.state"=>0,
        ])->field("s.*,u.phone") ->order("s.id desc")-> paginate());
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }
    /**
     * 店铺信息（店铺认证）
     * @param Request $R
     * @param S $s
     */
    public function save2(Request $R){
        $data=$R->post();
        $r=[
            "name|名称"=>"require",
            "storename|店铺名称"=>"require",
            "code|短信"=>"require|number", 
            "itype|身份证类型"=>"require",
//          "identity_id|身份证"=>"require|max:18|^[0-9]{17}[0-9A-Za-z]{1}$",
            "identity_id|身份证号"=>"require|max:18",
            "identityurl|手持身份证照"=>"require",
            "identityurl|手持身份证照"=>"require",
            "identity_url|身份证照正反面"=>"require|array",
        ];
        Ret::IfNoTrue($this->validate($R->post(), $r), 10200);
        if($data['code'] != Session::get("sms_code")){
            Ret::err(10300, "短信验证码错误");
        }
        $r1=[
            "main|主运营"=>"require",
            "license|营业执照"=>"require",
        ];
        Ret::IfNoTrue($this->validate($R->post(), $r1), 10201);
        $d= Db::table("store")->where([
            "store_name"=>$data['storename'],
            "business_id"=> Session::get("user.id"),
        ])->find();
        Ret::IfEmpty($d, 12222,"门店不存在");
        Db::table("users")->where([
            "higherups"=>Session::get("user.id"),
            "id"=>Session::get("sms_u_id"),
        ])->update([
            "name"=>$data['name'],
            "itype"=>$data['itype']
        ]);
        Db::table("identity")->insert([
            "user_id"=>Session::get("sms_u_id"),
            "createtime"=>date("Y-m-d H:i:s"),
            "name"=>$data['name'],
            "identity_id"=>$data['identity_id'],
            "identityurl"=> json_encode($data['identityurl']),
            "identity_url"=>$data['identity_url']
        ]);
       Db::table("store")->where([
           "id"=>Session::get("sms_id")
       ])->update([
           "main"=>$data['main'],
           "license"=>$data['license']
       ]);
       Ret::ok();
        
    }
    /**
     * 发送短信
     * @param AliYunSms $AliYunSms
     * @param string $storename 门店名称
     */
    public function sms(AliYunSms $AliYunSms, Request $R){
        Ret::IfNoTrue($this->validate($R->get(), ["storename|门店名称"=>"require"]) ,12133);
        $d= Db::table("store")->alias("s")->join("users u","u.id=s.user_id")->where([
            "s.store_name"=>$R->get("storename"),
            "s.business_id"=> Session::get("user.id"),
        ])->field("s.*,u.phone") ->find();
        Ret::IfEmpty($d, 12222,"门店不存在");
        if(! $d['phone']){
            Ret::err(10233,"无电话");
        }
        $code= rand(1000, 9999);
        Session::set("sms_code",$code);
        Session::set("sms_u_id",$d['user_id']);
        Session::set("sms_id",$d['id']);

        return $AliYunSms->code_type($code) ->setRecNum($d['phone']);
    }
    /**
     * 创建门店
     * @param Request $request
     * @param S $s
     */
    public function save(Request $request,S $s)
    {
        $rule=[
            "store_name|门店名称"=>"require|chsDash",
            "store_description|门店描述"=>"max:255",
            "phone|手机号码"=>"require|number",
            "date|时间"=>"require|date",
            "address|地址"=>"require",
        ];
       $ret= $this->validate($request->post() ,$rule );
       Ret::IfNoTrue($ret, 10120);
       $u=Db::table("users")->where([
           "phone"=>$request->post('phone'),
           "state"=>0
       ])->find();
       if(empty($u)){
           $id= Db::table("users")->insertGetId([
                    "superior_id" => Session::get("user.id"),
                     "system_id"=>1,
                     "is_business"=>0,
                    "higherups"=>Session::get("user.id"),
                     "phone"=>$request->post("phone")
                 ]);
       }else{
           if($u['is_business'] != 0){
               Ret::err(10300,"已经是商家，不可以改为门店");
           }
           if($u['shop'] !=0){
               Ret::err(10301,"已经是门店");
           }
           $id=$u['id'];
       }
      
      $d=$request->post();
       unset($d['phone']);
        ReturnData::IfTrue($ret, 11101);
        $data = Eliminate::E($d, $rule);
        $data['business_id']=Session::get("user.id");
        $data['store_logurl']=$request->post("store_logurl");
        $data['createtime']=date("Y-m-d H:i:s");
        $data['user_id']=$id;
        $data['state']=0;
        $s->insert($data);
        ReturnData::ok();
       
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 
     * 保存更新的资源
     *
     * @return \think\Response
     * @param Request $request
     * @param S $s
     * @param type $id  门店id
     */
    public function update(Request $request,S $s, $id)
    {
        $rule=[
            "store_name|门店名称"=>"require|chsDash",
            "store_description|门店描述"=>"max:255",
            "phone|手机号码"=>"require|number",
            "date|时间"=>"require|date",
            "address|地址"=>"require",
        ];

        $ret= $this->validate($request->post() ,$rule );
        Ret::IfNoTrue($ret, 11105);
//        $filename=$this->SetUploadDir("tjx")->Uploads_("store_logurl");
        $data = Eliminate::E($request->post(), $rule);
//        if($filename){
//            $data['store_logurl']=$filename;
//        }
        $data['store_logurl'] =$request->post("store_logurl");
        unset($data['phone']);
        $d=$s->where([
            "id"=>$id,
            'business_id'=>Session::get("user.id"),
            ])
        ->update($data);

        $dx=$s->where([
            "id"=>$id,
            'business_id'=>Session::get("user.id"),
            ])->find()->toarray();
        Db::table("users")->where([
            "id"=>$dx['user_id']
        ])->update([
            "phone"=>$request->post("phone")
        ]);
//        ReturnData::exit_( $d , 11104,"无任何修改或无数据");
        Ret::ok();
    }

    /**
     * 删除指定资源
     * @param  int  $id
     * @return \think\Response
     */
    public function delete(S $s,$id)
    {
        //
        ReturnData::exit_(
                $s->where([
                        'business_id'=>Session::get("user.id"),
                        "state"=>0,
                        "id"=>$id
                    ])->update(["state"=>1,])
                ,
                11103
                ,
                [],
                "删除失败，无权操作或意见被删除"
            );
    }
}
